import type { ConversionError } from '@/types'

// MCP服务器配置接口
interface McpServerConfig {
  command?: string
  args?: string[]
  env?: Record<string, string>
  startup_timeout_ms?: number
}

// 单个MCP配置接口
interface McpResource {
  uri?: string
  name?: string
  description?: string
  mimeType?: string
}

interface McpTool {
  name?: string
  description?: string
  inputSchema?: Record<string, unknown>
}

interface McpPrompt {
  name?: string
  description?: string
  arguments?: Record<string, unknown>
}

// MCP配置接口 - 支持多种配置格式
interface McpConfig {
  mcpServers?: Record<string, McpServerConfig>
  resources?: McpResource[]
  tools?: McpTool[]
  prompts?: McpPrompt[]
  // 单个MCP服务器配置
  type?: string
  url?: string
  alwaysAllow?: string[]
  // 其他可能的配置项
  [key: string]: unknown
}

// 转换MCP配置的特定逻辑
function convertMcpConfig(
  config: McpConfig,
  addOSEnv: boolean,
  targetOS: 'windows' | 'linux' | 'macos' = 'windows',
): McpConfig {
  // 如果不是对象，直接返回
  if (typeof config !== 'object' || config === null) {
    return config
  }

  // 深拷贝配置以避免修改原始对象
  const converted: McpConfig = JSON.parse(JSON.stringify(config))

  // 处理mcpServers配置
  if (converted.mcpServers && typeof converted.mcpServers === 'object') {
    for (const [, serverConfig] of Object.entries(converted.mcpServers)) {
      if (serverConfig && typeof serverConfig === 'object') {
        // 确保command是字符串
        if (serverConfig.command !== undefined) {
          serverConfig.command = String(serverConfig.command)
        }

        // 处理args数组
        if (serverConfig.args && Array.isArray(serverConfig.args)) {
          serverConfig.args = serverConfig.args.map((arg: unknown) => String(arg))
        }

        // 处理环境变量 - 只有在源JSON中存在env时才处理
        if (serverConfig.env && typeof serverConfig.env === 'object') {
          // 添加操作系统特定的环境变量
          if (addOSEnv) {
            if (targetOS === 'windows' && !serverConfig.env.SystemRoot) {
              serverConfig.env.SystemRoot = 'C:\\\\Windows'
            } else if (targetOS === 'linux' && !serverConfig.env.PATH) {
              serverConfig.env.PATH = '/usr/local/bin:/usr/bin:/bin'
            } else if (targetOS === 'macos' && !serverConfig.env.PATH) {
              serverConfig.env.PATH = '/usr/local/bin:/usr/bin:/bin'
            }
          }

          // 确保env中的所有值都是字符串
          for (const [key, value] of Object.entries(serverConfig.env)) {
            serverConfig.env[key] = String(value)
          }
        } else if (addOSEnv) {
          // 只有在勾选了添加Windows环境变量且源JSON中没有env时，才创建env对象
          serverConfig.env = {}
          if (targetOS === 'windows') {
            serverConfig.env.SystemRoot = 'C:\\\\Windows'
          } else if (targetOS === 'linux') {
            serverConfig.env.PATH = '/usr/local/bin:/usr/bin:/bin'
          } else if (targetOS === 'macos') {
            serverConfig.env.PATH = '/usr/local/bin:/usr/bin:/bin'
          }
        }

        // 只有在源JSON中存在startup_timeout_ms时才保留，或者勾选了添加Windows环境变量时才添加默认值
        if (serverConfig.startup_timeout_ms !== undefined) {
          // 保持原值
        } else if (addOSEnv) {
          // 只有在勾选了添加Windows环境变量时才添加默认值
          serverConfig.startup_timeout_ms = 20000
        }
      }
    }
  }

  return converted
}

// 转换值为TOML格式的字符串
function convertValueToToml(value: unknown, indent: number = 0, forceInline: boolean = false): string {
  const indentStr = '  '.repeat(indent)

  if (value === null || value === undefined) {
    return ''
  }

  if (typeof value === 'string') {
    // 处理包含特殊字符的字符串
    if (value.includes('\n') || value.includes('"')) {
      return `'''${value}'''`
    }
    return `"${value}"`
  }

  if (typeof value === 'number' || typeof value === 'boolean') {
    return String(value)
  }

  if (Array.isArray(value)) {
    if (value.length === 0) {
      return '[]'
    }

    // 检查是否是简单字符串数组
    const isSimpleStringArray = value.every(
      (item) =>
        typeof item === 'string' &&
        !item.includes('\n') &&
        !item.includes('"') &&
        !item.includes(','),
    )

    if (isSimpleStringArray) {
      // 避免最后一项有尾随逗号
      const items = value.map((item) => `"${item}"`)
      return `[ ${items.join(', ')} ]`
    }

    // 复杂数组，多行格式
    let result = '[\n'
    value.forEach((item, index) => {
      result += `${indentStr}  ${convertValueToToml(item, indent + 1, forceInline)}`
      // 避免最后一项有尾随逗号
      if (index < value.length - 1) {
        result += ','
      }
      result += '\n'
    })
    result += `${indentStr}]`
    return result
  }

  if (typeof value === 'object') {
    if (Object.keys(value).length === 0) {
      return '{}'
    }

    // 如果强制使用单行格式
    if (forceInline) {
      const entries = Object.entries(value)
      const items = entries.map(([key, val]) => `${key} = ${convertValueToToml(val, 0, forceInline)}`)
      return `{ ${items.join(', ')} }`
    }

    // 默认多行格式
    let result = '{\n'
    const entries = Object.entries(value)
    entries.forEach(([key, val], index) => {
      result += `${indentStr}  ${key} = ${convertValueToToml(val, indent + 1, forceInline)}`
      // 避免最后一项有尾随逗号
      if (index < entries.length - 1) {
        result += ','
      }
      result += '\n'
    })
    result += `${indentStr}}`
    return result
  }

  return ''
}

// 自定义TOML序列化函数，专门用于MCP配置
function customMcpTomlStringify(
  obj: McpConfig,
  addOSEnv: boolean = false,
  targetOS: 'windows' | 'linux' | 'macos' = 'windows',
): string {
  const converted = convertMcpConfig(obj, addOSEnv, targetOS)

  let tomlString = ''

  // 检查是否是单个MCP配置（包含type、url等字段）
  if (converted.type || converted.url) {
    // 单个MCP配置
    Object.entries(converted).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        if (key === 'alwaysAllow' && Array.isArray(value)) {
          // 特殊处理alwaysAllow数组，避免最后一项有尾随逗号
          const items = value.map((item) => `"${item}"`)
          tomlString += `alwaysAllow = [ ${items.join(', ')} ]\n`
        } else {
          tomlString += `${key} = ${convertValueToToml(value, 0, false)}\n`
        }
      }
    })
  } else {
    // 处理mcpServers配置
    if (converted.mcpServers && typeof converted.mcpServers === 'object') {
      for (const [serverName, serverConfig] of Object.entries(converted.mcpServers)) {
        if (serverConfig && typeof serverConfig === 'object') {
          // 服务器配置标题 - 使用下划线命名约定
          tomlString += `[mcp_servers.${serverName}]\n`

          Object.entries(serverConfig).forEach(([key, value]) => {
            if (value !== undefined && value !== null) {
              if (key === 'env') {
                // 特殊处理环境变量对象，使用单行格式
                tomlString += `env = ${convertValueToToml(value, 0, true)}\n`
              } else if (key === 'args') {
                // 特殊处理args数组
                tomlString += `args = ${convertValueToToml(value)}\n`
              } else {
                tomlString += `${key} = ${convertValueToToml(value)}\n`
              }
            }
          })

          tomlString += '\n'
        }
      }
    }

    // 处理其他配置项
    ;['resources', 'tools', 'prompts'].forEach((section) => {
      if (
        converted[section] &&
        Array.isArray(converted[section]) &&
        converted[section].length > 0
      ) {
        tomlString += `[[${section}]]\n`
        converted[section].forEach((item: unknown) => {
          if (item && typeof item === 'object') {
            Object.entries(item).forEach(([key, value]) => {
              if (value !== undefined && value !== null) {
                tomlString += `${key} = ${convertValueToToml(value, 0, false)}\n`
              }
            })
          }
          tomlString += '\n'
        })
      }
    })
  }

  return tomlString.trim()
}

export function jsonToToml(
  json: string,
  addOSEnv: boolean = false,
  targetOS: 'windows' | 'linux' | 'macos' = 'windows',
): {
  success: boolean
  toml?: string
  error?: ConversionError
} {
  try {
    // 解析JSON
    const parsed = JSON.parse(json) as McpConfig

    // 使用自定义的MCP TOML序列化函数
    const tomlString = customMcpTomlStringify(parsed, addOSEnv, targetOS)

    return {
      success: true,
      toml: tomlString,
    }
  } catch (error) {
    return {
      success: false,
      error: {
        type: 'conversion',
        message: `转换失败: ${error instanceof Error ? error.message : '未知错误'}`,
        details: error,
      },
    }
  }
}

// 验证转换后的TOML格式
export function validateTomlOutput(toml: string): { isValid: boolean; error?: string } {
  try {
    // 基本的TOML格式验证
    const lines = toml.split('\n')
    let bracketCount = 0

    for (const line of lines) {
      const trimmed = line.trim()
      if (!trimmed || trimmed.startsWith('#')) continue

      // 检查括号匹配
      for (const char of trimmed) {
        if (char === '[') bracketCount++
        else if (char === ']') bracketCount--
      }
    }

    if (bracketCount !== 0) {
      return { isValid: false, error: 'TOML格式错误：括号不匹配' }
    }

    return { isValid: true }
  } catch (error) {
    return {
      isValid: false,
      error: error instanceof Error ? error.message : 'TOML格式无效',
    }
  }
}

// 格式化TOML输出
export function formatTomlOutput(toml: string): string {
  try {
    // 基本的TOML格式化
    const lines = toml.split('\n')
    const formattedLines: string[] = []

    for (const line of lines) {
      const trimmed = line.trim()
      if (trimmed) {
        formattedLines.push(trimmed)
      }
    }

    return formattedLines.join('\n').trim()
  } catch {
    return toml
  }
}

// 获取转换统计信息
export function getConversionStats(
  json: string,
  toml: string,
): {
  jsonSize: number
  tomlSize: number
  compressionRatio: number
  serverCount: number
} {
  const jsonSize = new Blob([json]).size
  const tomlSize = new Blob([toml]).size
  const compressionRatio = jsonSize > 0 ? (tomlSize / jsonSize) * 100 : 0

  let serverCount = 0
  try {
    const parsed = JSON.parse(json) as McpConfig
    if (parsed.mcpServers && typeof parsed.mcpServers === 'object') {
      serverCount = Object.keys(parsed.mcpServers).length
    } else if (parsed.type || parsed.url) {
      serverCount = 1 // 单个MCP配置
    }
  } catch {
    // 忽略解析错误
  }

  return {
    jsonSize,
    tomlSize,
    compressionRatio,
    serverCount,
  }
}
